// 插件状态
let pluginEnabled = false;
let observer = null; // 保存observer引用
let isMonitoring = false; // 跟踪监控状态

// 添加尺寸阈值变量
let widthThreshold = 0;
let heightThreshold = 0;

// 从本地存储加载阈值设置
chrome.storage.local.get(
  ["widthThreshold", "heightThreshold", "pluginEnabled"],
  (result) => {
    widthThreshold = result.widthThreshold || 150;
    heightThreshold = result.heightThreshold || 150;
    pluginEnabled = result.pluginEnabled || false;
    if (pluginEnabled) {
      startMonitoring();
    }
  }
);

// 修改消息监听，处理阈值更新
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
  console.log("已经从content-scripts接受信息:");
  console.log(message);
  if (message.action === "togglePlugin") {
    pluginEnabled = message.enabled;
    if (pluginEnabled) {
      startMonitoring();
    } else {
      stopMonitoring(); //停止监控
      reprocessMediaElements(); // 清除页面添加的下载按钮
    }
  } else if (message.action === "updateThresholds") {
    // 更新阈值并重新处理媒体元素
    widthThreshold = message.width || 150;
    heightThreshold = message.height || 150;
    if (pluginEnabled) {
      reprocessMediaElements(); // 清除现有按钮并重新处理
    }
  }
});

// 开始监控页面元素
function startMonitoring() {
  console.log("开始监控方法执行");
  if (isMonitoring) return;
  if (observer) observer.disconnect();

  processMediaElements();

  observer = new MutationObserver((mutations) => {
    mutations.forEach((mutation) => {
      if (mutation.addedNodes.length) processMediaElements();
    });
  });

  observer.observe(document.body, { childList: true, subtree: true });
  isMonitoring = true;
  console.log("监控已启动-完成");
}

// 停止监控
function stopMonitoring() {
  console.log("停止监控方法执行");

  if (observer) observer.disconnect();
  isMonitoring = false;
  console.log("监控已停止-完成");
}

// 处理媒体元素
function processMediaElements() {
  if (!pluginEnabled) return;
  // 处理图片
  document
    .querySelectorAll("img:not([data-download-processed])")
    .forEach((img) => processImage(img));
  // 处理视频
  document
    .querySelectorAll("video:not([data-download-processed])")
    .forEach((video) => processVideo(video));
}

// 处理图片元素
function processImage(img) {
  // 检查尺寸是否超过阈值
  if (widthThreshold > 0 || heightThreshold > 0) {
    const imgWidth = img.offsetWidth;
    const imgHeight = img.offsetHeight;

    if (imgWidth < widthThreshold || imgHeight < heightThreshold) {
      img.setAttribute("data-download-processed", "true"); // 标记为已处理但不添加按钮
      return;
    }
  }
  img.setAttribute("data-download-processed", "true");
  const url = img.src;
  if (url) createImageDownloadButton(img, url);
}

// 处理视频元素
function processVideo(video) {
  // 检查尺寸是否超过阈值
  if (widthThreshold > 0 || heightThreshold > 0) {
    const videoWidth = video.offsetWidth;
    const videoHeight = video.offsetHeight;

    if (videoWidth < widthThreshold || videoHeight < heightThreshold) {
      video.setAttribute("data-download-processed", "true"); // 标记为已处理但不添加按钮
      return;
    }
  }
  video.setAttribute("data-download-processed", "true");
  const videoUrl = video.src || video.firstElementChild?.src || "";
  if (videoUrl) createVideoDownloadButton(video, videoUrl);
}

// 删除页面元素
function reprocessMediaElements() {
  // 先移除下载图标
  document
    .querySelectorAll(".media-download-icon")
    .forEach((icon) => icon.remove());

  // 处理媒体包装器，恢复原始元素结构
  document.querySelectorAll(".media-wrapper").forEach((wrapper) => {
    const parent = wrapper.parentNode;
    // 将包装器内的原始媒体元素移回原位置
    while (wrapper.firstChild) {
      parent.insertBefore(wrapper.firstChild, wrapper);
    }
    // 移除空包装器
    wrapper.remove();
  });

  // 清除处理标记
  document
    .querySelectorAll("[data-download-processed]")
    .forEach((el) => el.removeAttribute("data-download-processed"));

  // 重新处理所有媒体元素 - 取消注释这行
  processMediaElements();
}

// 创建下载按钮(图片)
function createImageDownloadButton(
  element,
  url,
  isBase64 = false,
  imageType = "jpg"
) {
  createMediaDownloadButton(element, url, "image", isBase64, imageType);
}

// 创建下载按钮(视频)
function createVideoDownloadButton(element, url) {
  createMediaDownloadButton(element, url, "video");
}

// 通用的媒体下载按钮创建函数
function createMediaDownloadButton(
  element,
  url,
  mediaType,
  isBase64 = false,
  imageType = "jpg"
) {
  console.log("createMediaDownloadButton方法开始运行-包装器，创建div");

  // 创建包装器div
  const wrapper = document.createElement("div");
  wrapper.className = "media-wrapper";
  wrapper.style.position = "relative";
  wrapper.style.display = "inline-block";

  // 动态获取媒体元素宽高并应用到wrapper
  const width = element.offsetWidth + "px";
  const height = element.offsetHeight + "px";
  wrapper.style.width = width;
  wrapper.style.height = height;

  // 存储媒体信息到包装器
  wrapper.dataset.mediaUrl = url;
  wrapper.dataset.mediaType = mediaType;

  // 创建下载图标
  const downloadIcon = document.createElement("img");
  downloadIcon.src = chrome.runtime.getURL("/src/image/icon_18.png"); // 使用public文件夹中的图标
  downloadIcon.style.position = "absolute";
  downloadIcon.style.bottom = "5px";
  downloadIcon.style.right = "5px";
  downloadIcon.style.width = "24px";
  downloadIcon.style.height = "24px";
  downloadIcon.style.cursor = "pointer";
  downloadIcon.style.zIndex = "9999";
  downloadIcon.className = "media-download-icon";
  wrapper.appendChild(downloadIcon);

  // 获取父节点并插入包装器
  const parentNode = element.parentNode;
  parentNode.insertBefore(wrapper, element);
  wrapper.appendChild(element);
  console.log("运行完成-包装器");
}

// 添加事件委托处理伪元素点击
document.addEventListener("click", (event) => {
  const downloadIcon = event.target.closest(".media-download-icon");
  console.log("click方法开始运行-事件委托，点击事件");
  if (downloadIcon) {
    const wrapper = downloadIcon.closest(".media-wrapper");
    if (wrapper) {
      event.stopImmediatePropagation();
      event.preventDefault();
      chrome.runtime.sendMessage({
        action: "downloadMedia",
        url: wrapper.dataset.mediaUrl,
        type: wrapper.dataset.mediaType,
      });
      console.log("click-点击完成");
    }
  }
});
